<template>
  <n-space vertical>
    <n-h1 prefix="bar">
      <n-text type="primary">
        用户列表
      </n-text>
    </n-h1>
    <n-button type="primary" @click="showAddModel=true">添加新用户</n-button>
    <n-table>
      <thead>
      <tr>
        <th>ID</th>
        <th>用户名</th>
        <th>姓名</th>
        <th>邮箱</th>
        <th>管理员</th>
        <th>激活</th>
        <th>加入时间</th>
        <th>最后登录时间</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="item in userlist" :key="item.id">
        <td>{{item.id}}</td>
        <td>{{item.username}}</td>
        <td>{{item.first_name}} {{item.last_name}}</td>
        <td>{{item.email}}</td>
        <td><n-tag v-if="item.is_superuser" type="success">是</n-tag><n-tag v-else type="error">否</n-tag></td>
        <td><n-tag v-if="item.is_active" type="success">是</n-tag><n-tag v-else type="error">否</n-tag></td>
        <td>{{item.date_joined}}</td>
        <td>{{item.last_login}}</td>
        <td>
          <n-space>
            <n-button type="primary" size="small" @click="showEdit(item)">编辑</n-button>
            <n-button type="warning" size="small" @click="showResetPassword(item)">重置密码</n-button>
            <n-popconfirm
                @positive-click="handlePositiveClick(item.id)"
                @negative-click="handleNegativeClick"
                negative-text="取消"
                positive-text="确定"
            >
              <template #trigger>
                <n-button type="error" size="small">删除</n-button>
              </template>
              删除操作不可逆，请谨慎操作
            </n-popconfirm>
          </n-space>
        </td>
      </tr>
      </tbody>
    </n-table>
    <n-pagination
        v-model:page="pageOptions.page"
        :page-count="pageOptions.maxPage"
        @update:page="loadUserList"
        @update:pageSize="loadUserList"
    />
  </n-space>
  <n-modal v-model:show="showAddModel" title="添加新用户">
    <n-card
        style="width: 600px"
        title="添加用户"
        size="huge"
    >
      <n-form>
        <n-form-item label="用户名">
          <n-input placeholder="请输入用户名" v-model:value="newUser.username"></n-input>
        </n-form-item>
        <n-form-item label="密码">
          <n-input placeholder="请输入密码" v-model:value="newUser.password"></n-input>
        </n-form-item>
      </n-form>
      <template #footer>
        <n-space>
          <n-button type="primary" @click="addUser">添加</n-button>
          <n-button type="primary" @click="closeAddModel">取消</n-button>
        </n-space>
      </template>
    </n-card>
  </n-modal>
  <n-modal v-model:show="showEditModel" title="编辑用户">
    <n-card
        style="width: 600px"
        title="编辑用户"
        size="huge"
    >
      <n-form>
        <n-form-item label="用户名">
          <n-input placeholder="请输入用户名" v-model:value="editUser.username" disabled="False"></n-input>
        </n-form-item>
        <n-form-item label="姓名">
          <n-input-group>
            <n-input placeholder="姓" v-model:value="editUser.first_name"></n-input>
            <n-input placeholder="名" v-model:value="editUser.last_name"></n-input>
          </n-input-group>
        </n-form-item>
        <n-form-item label="邮箱">
          <n-input placeholder="请输入邮箱" v-model:value="editUser.email"></n-input>
        </n-form-item>
        <n-form-item label="管理员">
          <n-switch v-model:value="editUser.is_superuser"></n-switch>
        </n-form-item>
        <n-form-item label="激活">
          <n-switch v-model:value="editUser.is_active"></n-switch>
        </n-form-item>
      </n-form>
      <template #footer>
        <n-space>
          <n-button type="primary" @click="changeUser">修改</n-button>
          <n-button type="primary" @click="closeEditModel">取消</n-button>
        </n-space>
      </template>
    </n-card>
  </n-modal>
  <n-modal v-model:show="showResetPasswordModel" title="重置用户密码">
    <n-card
        style="width: 600px"
        title="重置用户密码"
        size="huge"
    >
      <n-form>
        <n-form-item label="ID" v-show="false">
          <n-input v-model:value="resetUser.id" disabled v-show="false"></n-input>
        </n-form-item>
        <n-form-item label="新密码">
          <n-input placeholder="请输入新密码" v-model:value="resetUser.password"></n-input>
        </n-form-item>
        <n-form-item label="确认密码">
          <n-input placeholder="请确认密码" v-model:value="confirmPassword"></n-input>
        </n-form-item>
      </n-form>
      <template #footer>
        <n-space>
          <n-button type="success" @click="resetUserPassword">确认</n-button>
          <n-button type="error" @click="closeResetPasswordModal">取消</n-button>
        </n-space>
      </template>
    </n-card>
  </n-modal>
</template>

<script setup lang="ts">

import {userAdd, userDelete, userList, userUpdate} from "/@api/hz-system-admin-api";
import {changePassword} from "/@api/hz-system-api";
import {useUserConfig} from "/@bean/GlobalConfig";
import {storeToRefs} from "pinia";
import router from "/@/router";
const storesUserConfig = useUserConfig();
const { userInfo } = storeToRefs(storesUserConfig);

const currentUser = userInfo.value.username
const userlist = ref([])
const showAddModel = ref(false)
const showEditModel = ref(false)
const showResetPasswordModel = ref(false)

let message = useMessage();

let newUser = reactive({
  username: '',
  password: ''
})

let confirmPassword = ref('')
let resetUser = reactive({
  id: 0,
  password: ''
})
let currentResetUserName = ref('')

let editUser = reactive({})

let pageOptions = reactive({
  page: 1,
  size: 10,
  maxPage: 100
})


onMounted(() => {
  loadUserList()
})

// 获取用户列表
const loadUserList = async () => {
  let users = await userList({
    page: pageOptions.page,
    size: pageOptions.size
  })
  if(users.code !== 200){
    message.error(users.msg);
  }
  pageOptions.maxPage = users.data.totalPage
  userlist.value = users.data.items
}

// 添加用户
const addUser = async () => {
  console.log(newUser)
  let res = await userAdd(newUser)
  if (res.code === 200) {
    await loadUserList()
    closeAddModel()
    message.success(res.msg);
  }else{
    message.error(res.msg);
  }
}

// 删除用户
const deleteUser = async (id: number) => {
  let result = await userDelete({
    id: id
  })
  if (result.code === 200) {
    await loadUserList()
    message.success(result.msg);
  }else{
    message.error(result.msg);
  }
}

// 编辑用户
const changeUser = async () => {
  let res = await userUpdate(editUser)
  if (res.code === 200) {
    await loadUserList()
    closeEditModel()
    message.success(res.msg);
  }else{
    message.error(res.msg);
  }
}

// 显示编辑用户模态框
function showEdit(item:any) {
  showEditModel.value = true
  editUser = item
}

// 显示重置密码模态框
function showResetPassword(item:any) {
  showResetPasswordModel.value = true
  resetUser.id = item.id
  currentResetUserName.value = item.username
}

function closeAddModel() {
  showAddModel.value = false
  newUser.username = ''
  newUser.password = ''
}

function closeResetPasswordModal() {
  showResetPasswordModel.value = false
  resetUser.password = ''
  resetUser.id = 0
  confirmPassword.value = ''
  currentResetUserName.value = ''
}

function closeEditModel() {
  showEditModel.value = false
  editUser = {}
  loadUserList()
}

function handlePositiveClick(id:number) {
  deleteUser(id)
}

function handleNegativeClick() {
  message.info('取消删除');
}

// 重置用户密码
function resetUserPassword() {
  if (resetUser.password === '' || confirmPassword.value === '') {
    message.error('密码不能为空');
    return;
  }
  if (resetUser.password !== confirmPassword.value) {
    message.error('两次密码不一致');
    return;
  }
  changePassword(resetUser).then((res) => {
    if (res.code === 200) {
      message.success('重置用户{'+currentResetUserName.value +'}密码成功');
      console.log('currentResetUserName',currentResetUserName.value)
      console.log('current',currentUser)
      //   如果重置的是当前登录的管理员，则需要重新登录
      if (currentResetUserName.value === currentUser) {
        message.success('即将跳转到登录页面...');
        //   等待3s
        setTimeout(() => {
          storesUserConfig.clearUserInfo()
          router.push('/login');
        }, 3000);
      }
    } else {
      message.error(res.msg);
    }
      closeResetPasswordModal()
  });
}
</script>

<style scoped>

</style>